package com.wt.hrentSystem.common.util;



import com.wt.hrentSystem.common.entity.TreeEntity;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

public abstract class TreeUtils {
    public static <T extends TreeEntity> List<T> getTreeData(List<T> list){

        //最后的结果
        List<T> resultList = new ArrayList<>();
        //先找到所有的一级菜单
        for(int i = 0;i<list.size();i++){
            //一级菜单没有parientId
            if(StringUtils.isBlank(list.get(i).getParentId())){
                resultList.add(list.get(i));
            }
        }
        //为一级菜单设置子菜单，getChild是递归调用的
        for (T treeEntity : list) {
            treeEntity.setChildren(getChild(treeEntity.getId(),list));
        }
        return resultList;
    }
    private static <T extends TreeEntity> List<T> getChild(String id, List<T> list){
        //子菜单
        List<T> childList = new ArrayList<>();
        for (T treeEntity : list) {
            //遍历所有节点，将父级id与传过来的id比较
            if(StringUtils.isNotBlank(treeEntity.getParentId())){
                if(treeEntity.getParentId().equals(id)){
                    childList.add(treeEntity);
                }
            }
        }
        //把子菜单的子菜单再循环一遍
        for (T treeEntity : childList) {
            if(treeEntity.isExistChildren()){
                treeEntity.setChildren(getChild(treeEntity.getId(),list));
            }
        }
        //递归退出条件
        if(childList.size()==0){
            return null;
        }
        return childList;
    }
}
